package com.hn658.groupshare.security.service.impl;

import java.io.ByteArrayInputStream;
import java.net.URLEncoder;

import javax.annotation.PostConstruct;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hn658.framework.logging.Logger;
import com.hn658.framework.logging.LoggerFactory;
import com.hn658.framework.logging.enums.LogCategory;
import com.hn658.framework.security.cryptography.Digests;
import com.hn658.framework.security.cryptography.HexBinrary;
import com.hn658.groupshare.config.service.IGroupShareConfig;
import com.hn658.groupshare.security.service.ISmsService;

@Service
public class SmsServiceImpl implements ISmsService {

	private static Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);
	
	@Autowired
	private IGroupShareConfig config; 

    /**
     * 签名
     */
    private String sign;

    private HttpClient httpClient;

    @SuppressWarnings("unused")
	@PostConstruct
    private void afterInitialization() throws Exception{
        String str = config.getClient5173key() + config.getClient5173IP();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes("gb2312"));
        byte[] byteArray = Digests.md5(inputStream);
        sign = HexBinrary.encodeHexBinrary(byteArray).toLowerCase();

        httpClient = new DefaultHttpClient();
        logger.debug(LogCategory.SYSTEM,String.format("5173短信平台客户端clientIP:%s,key:%s,category:%s,weburl:%s,sign:%s",
        		config.getClient5173IP(), config.getClient5173key(), 
        		config.getClient5173Category(), config.getClient5173RequestUrl(), sign));
    }

    public void sendVerifyCode(String phone, String code) {
        String request = null;
        try {
            request = String.format(config.getClient5173RequestUrl(), sign, config.getClient5173IP(), config.getClient5173Category(), phone,
                    URLEncoder.encode(String.format("【658短信通知】，感谢您的关注及支持，您的本次验证码为%s，请勿让他人知晓。", code), "UTF-8"));
            logger.debug("5173短信平台发送URL:{}", request);
            HttpResponse response = httpClient.execute(new HttpGet(request));
            logger.debug(LogCategory.SYSTEM,String.format("5173短信平台发送给手机终端{}结果：{}", phone,
                    IOUtils.toString(response.getEntity().getContent())));
        } catch (Exception e) {
            logger.error("发送短信发生异常：{}", ExceptionUtils.getStackTrace(e));
        }

    }
}
